<template>
  <div class="upload-files">
    <!-- 上传按钮 -->
    <el-upload
      class="upload"
      v-if="!disabled"
      :show-file-list="false"
      :headers="headers"
      :limit="1"
      :action="action"
      accept=""
      name="file"
      :on-success="handleChange"
      list-type="picture"
      :file-list="fileList"
      :before-upload="beforeUpload"
    >
      <el-button size="small" type="primary">{{ title }}</el-button>
    </el-upload>
    <!-- 上传结果，可排序 -->
    <div class="upload-list sort_area" id="sort_area">
      <div class="item btn_drag" :data-id="idx" v-for="(item, idx) in fileList" :key="idx">
        <div class="content" @click="handleItemClick(item, idx)"><i class="el-icon-document"></i> <Document class="icon_font" />{{ ` 附件${idx + 1}.${item.type}` }}</div>
        <span>
          <div style="float: left; margin-right: 19px">
            <el-icon class="icon_green" size="18">
              <CircleCheck />
            </el-icon>
          </div>
          <div style="float: right">
            <el-icon class="icon_red" size="18"> <CircleClose @click="handleRemove(item)" v-if="!disabled" class="icon_red"></CircleClose></el-icon>
          </div>
        </span>
      </div>
    </div>
    <!-- <template v-if="showPreviewer">
      <file-viewer :z-index="zIndex_a" :initial-index="previewerIndex" :url-list="reformFileListForPreviewer(fileList)" :onClose="handlePerviewerClose" />
    </template> -->
    <!-- 上传进度条 -->
    <el-progress v-if="showProgress" :percentage="percentage"></el-progress>
    <!-- <div ref="dialogContainer">
      <el-dialog title="预览" :visible.sync="dialogVisible" width="60%" top="2%" append-to-body>
        <pdf :src="src"></pdf>
      </el-dialog>
    </div> -->
  </div>
</template>

<script>
import { Document, CircleCheck, CircleClose } from '@element-plus/icons-vue';
// import FileViewer from './file-viewer.vue';
export default {
  components: {},
  props: {
    title: {
      type: String,
      default: ''
    },
    source: {
      type: String,
      default: ''
    },
    type: {
      type: Boolean,
      default: true
    },
    // 禁用上传，同时禁用排序
    disabled: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      action: '',
      sortable: undefined,
      orderResult: [],
      result: '',
      fileList: [], //上传列表
      showProgress: false,
      percentage: 0,
      timer: null,
      error: false,
      dialogVisible: false,
      src: '',
      headers: {
        Authorization: sessionStorage.getItem('token')
      },
      showPreviewer: false,
      previewerIndex: 100,
      zIndex_a: 100,
      typeList: ['.jpg', '.png', '.jpeg', '.bmp']
    };
  },
  created() {
    this.action = globalVar.requestbaseURL + '/soil/water/sys/app/save/uploadApp';
  },
  mounted() {
    //  创建排序对象
    const sortArea = document.getElementById('sort_area');
    const option = {
      sort: true,
      animation: 200,
      group: '',
      draggable: '.item', //可排序的对象
      handle: '.btn_drag', // 用来拖拽的元素
      disabled: this.disabled, //禁止排序
      dataIdAttr: 'data-id' // 用来标识排序对象顺序的固定字段
    };
    // this.sortable = Sortable.create(sortArea, option);
    this.fileList = [];
    try {
      if (this.source) {
        this.fileList = this.source.split(',').map((element, index) => {
          return {
            name: `附件${index + 1}`,
            url: element,
            type: element.split('.')[element.split('.').length - 1]
          };
        });
      }
    } catch (error) {}
  },
  watch: {
    source: {
      handler(val) {
        // 首次加载
        this.fileList = [];
        if (val && !this.fileList.length) {
          this.fileList = this.source.split(',').map((element, index) => {
            return {
              name: `附件${index + 1}`,
              url: element,
              type: element.split('.')[element.split('.').length - 1]
              // id: index
            };
          });
        }
      },
      deep: true
    },
    fileList: {
      handler(val) {
        if (val) {
          this.getFiles(val);
        }
      },
      deep: true
    }
  },
  methods: {
    // 重新拼接前缀
    reformFileListForPreviewer(files) {
      const res = files
        .filter((item) => (item.response ? item.response.object : item.url))
        .map((item) => (item.response ? item.response.object : item.url))
        .join(',');
      return res.split(',').map((url) => {
        const isImage = this.typeList.filter((item) => url.toLowerCase().includes(item)).length > 0;
        return {
          url: `${globalVar.picShowURL}/${url}`,
          isImage
        };
      });
    },
    handleOpen() {
      let _fileList = this.reformFileList(this.fileList);
      let type = _fileList[0].url.split('.')[_fileList[0].url.split('.').length - 1];
      if (_fileList.length == 1 && type == 'pdf') {
        this.dialogVisible = true;
        let src = _fileList[0].url;
        this.src = src;
      } else {
        this.dialogTableVisible = true;
      }
    },
    // 关闭图片预览
    handlePerviewerClose() {
      this.showPreviewer = false;
    },
    haddleDia(bool) {
      this.dialogVisible = bool;
      this.$refs.dialogContainer.lastChild.hidden = true;
    },
    // 关闭
    handleClose() {
      this.dialogTableVisible = false;
    },
    handleItemClick(item, index) {
      //   this.previewerIndex = index;
      //   this.showPreviewer = true;
      const url = encodeURI(`${item.response ? item.response.object : item.url}`);
      window.open(url);
    },
    beforeUpload() {
      this.showProgress = true;
      this.percentage = 70;
      this.autoRate();
    },
    // 进度初始化(异常及重新上传)
    initCircle() {
      this.percentage = 0;
      this.error = false;
    },
    autoRate() {
      clearTimeout(this.timer);
      if (this.error) return this.initCircle();
      // 渐变速度，根据实际效果做调整
      if (this.percentage < 99) {
        if (this.percentage < 70) {
          this.timer = setTimeout(() => {
            this.percentage += 1;
            this.autoRate();
          }, 50);
        } else if (this.percentage < 85) {
          this.timer = setTimeout(() => {
            this.percentage += 1;
            this.autoRate();
          }, 100);
        } else {
          this.timer = setTimeout(() => {
            this.percentage += 1;
            this.autoRate();
          }, 150);
        }
      }
    },
    //   上传文件
    handleChange(file, fileList) {
      let type = fileList.name.split('.')[fileList.name.split('.').length - 1];
      if (fileList.response.code == 1) {
        this.percentage = 100;
        this.$message.success('上传成功');
        this.fileList.push({
          name: fileList.name,
          url: fileList.response.object,
          type: fileList.name.split('.')[fileList.name.split('.').length - 1]
        });
        this.getFiles(this.fileList);
        this.$nextTick(() => {
          this.showProgress = false;
        });
      } else {
        this.$message.warning('上传失败');
      }
    },
    handleRemove(item) {
      this.fileList = this.fileList.filter((_item) => item.url !== _item.url);
    },
    // 获取文件列表
    getFiles(val) {
      //变更排序
      const res = this.fileList
        .filter((item) => (item ? item.url : ''))
        .map((item) => (item ? item.url : ''))
        .join(',');
      this.$emit('onImagesChange', res);
      return res;
    }
  }
};
</script>

<style lang="less" scoped>
.el-button {
  margin: 4px;
  background-color: #3f8cff;
  border: 1px solid #3f8cff;
  width: 87px;
  height: 32px;
  font-size: 14px;
}

.upload-list {
  .item {
    padding: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 240px;
    height: 30px;

    .content {
      display: flex;
      align-items: center;
      line-height: 23px;
      overflow: hidden;
      padding: 0;
      cursor: pointer;
      i {
        margin-right: 8px;
      }
    }

    .el-icon-circle-close {
      display: none;
    }

    .el-icon-circle-check {
      display: block;
      color: #67c23a;
    }

    &:hover {
      background-color: rgba(0, 0, 0, 0.15);

      .el-icon-circle-close {
        display: block;
      }

      .el-icon-circle-check {
        display: none;
      }
    }
  }
}
.icon_font {
  height: 18px;
}
.icon_green {
  height: 18px;
  display: block;
  color: #67c23a;
  float: left;
}
.icon_red {
  height: 18px;
  display: block;
  color: red;
  float: right;
  cursor: pointer;
}
</style>